quietly {

noisily: di	in yellow	"Grab a coffee or tea...{break}" " "

*-------------------------------------------------------------------------------*
* Structure of file
*
* 1. Parse input
* 2. Prepare estimation
* 3. Loop over countries and call models
* 4. Append files and clean up folder
*
* Version:	2016-10-17
* Changes:	2022-07-04: Added the possibility to choose between default and minister version of the main dataset
*
* Notes for nerds: If you are not satisfied with our preselection of models
*	and want to add new estimates you need to carefully complement this syntax.
*	I have provided as many notes as reasonable from my point of view. If you 
*	have any question do not hesitate to get in touch (data@nilsduepont.de).
*-------------------------------------------------------------------------------*



*-----------------------*
* 	1. PARSE INPUT		*
*-----------------------*


local countriesl "$countries" // "translate" global to local, which can be tokenized
di "`countriesl'"

tokenize `countriesl' // tokenize, i.e. grab country codes

local wordcount = wordcount("`countriesl'") // count how many countries are specified
di `wordcount'

clear // prepare variables for visual check of specified models
set obs `wordcount'
gen country	   		= ""
gen tmp_government 	= ""
gen tmp_minority   	= ""
gen tmp_vetoplayer	= ""

forvalues j = 1/`wordcount' {
	local country`j': word `j' of `countriesl' // grab first, second, third etc. country of list
	*di "`country`j''"
	
	local model "$`country`j''" // "translate" country global, which includes the model specification
	*di "`model'"
	
	replace country = "`country`j''" in `j' // write country to variable

	local gov: word 1 of `model' // grab government model
	*di "`gov'"
	replace tmp_government = "`gov'" in `j'

	local minor: word 2 of `model' // grab minority parties
	*di "`minor'"
	replace tmp_minority = "`minor'" in `j'

	local veto: word 3 of `model' // grab veto player
	*di "`veto'"
	replace tmp_vetoplayer = "`veto'" in `j'

}

* GOVERNMENT
gen tmp_gov1 = regexm(tmp_government,"cabmem")
gen tmp_gov2 = regexm(tmp_government,"seats")
gen tmp_gov3 = regexm(tmp_government,"portfolios")
gen tmp_gov4 = regexm(tmp_government,"pm")
gen tmp_gov5 = regexm(tmp_government,"minister")
gen tmp_gov6 = regexm(tmp_government,"pmnegot")
gen tmp_gov7 = regexm(tmp_government,"unanimity")
gen tmp_gov8 = regexm(tmp_government,"uwmean")
gen tmp_gov9 = regexm(tmp_government,"special_aspm")

gen government = ""
replace government = "cabmem"		if tmp_gov1==1
replace government = "seats"		if tmp_gov2==1
replace government = "portfolios"	if tmp_gov3==1
replace government = "pm"			if tmp_gov4==1
replace government = "minister"		if tmp_gov5==1
replace government = "pmnegot"		if tmp_gov6==1
replace government = "unanimity"	if tmp_gov7==1
replace government = "uwmean"		if tmp_gov8==1
replace government = "special_aspm"	if tmp_gov9==1

gen minister = ""
replace minister = substr(tmp_government, 14, .) if government == "minister"
replace minister = substr(tmp_government, 13, .) if government == "pmnegot"
replace minister = subinstr(minister, ")", "", .)


* MINORITY
gen tmp_minor = regexm(tmp_minority,"yes")
gen minority = ""
replace minority = "no"  if tmp_minor == 0
replace minority = "yes" if tmp_minor == 1

gen antisys = ""
replace antisys = substr(tmp_minority, 22, .) if minority == "yes"
replace antisys = subinstr(antisys, ")", "", .)


* VETO PLAYER
gen vetoplayer = ""
replace vetoplayer = substr(tmp_vetoplayer, 4, .)
replace vetoplayer = subinstr(vetoplayer, ")", "", .)


* Save temporary data set which governs estimation
lab var government "Your choice of the cabinet model"
lab var minister "Your choice of ministers"
lab var minority "Your choice whether minority gov. is considered"
lab var antisys "Your choice of anti-system parties excl. as support for minority gov."
lab var vetoplayer "Your choice of veto players"
drop tmp*
save tmp_modelspecs, replace



*-----------------------*
* 2. PREPARE ESTIMATION	*
*-----------------------*


* Generate smaller PIP to speed up estimation
local ds $dataset
if "`ds'" == "" {
	use "datasets/pip_ts_aspm", clear
	noisily: di	in yellow	"A short note: You are using the categorical (default) minister coding for modelling the ASPM...{break}" " "		
	}
else if "`ds'" == "minister" {
	use "datasets/pip_ts_aspm_minister", clear
	noisily: di	in yellow	"A short note: You are using the unique minister coding for modelling the ASPM...{break}" " "
	}
else {
	noisily: di	in yellow	"It seems like you did not properly specify which dataset to use..."	
}
keep id g??? p??? $ideology
save basic, replace


* Grab the model specs
use tmp_modelspecs, clear


* Assign proper ISO codes
capture: gen iso = .
capture: replace iso=36  if country=="AUS"
capture: replace iso=40  if country=="AUT"
capture: replace iso=56  if country=="BEL"
capture: replace iso=100 if country=="BGR" | country=="BUL"
capture: replace iso=124 if country=="CAN"
capture: replace iso=191 if country=="HRV" | country=="CRO"
capture: replace iso=196 if country=="CYP"
capture: replace iso=203 if country=="CZE"
capture: replace iso=208 if country=="DNK"
capture: replace iso=233 if country=="EST"
capture: replace iso=246 if country=="FIN"
capture: replace iso=250 if country=="FRA"
capture: replace iso=276 if country=="DEU" | country=="GER"
capture: replace iso=300 if country=="GRC"
capture: replace iso=348 if country=="HUN"
capture: replace iso=352 if country=="ISL" | country=="ICE"
capture: replace iso=372 if country=="IRL" | country=="IRE"
capture: replace iso=380 if country=="ITA"
capture: replace iso=392 if country=="JPN" | country=="JAP"
capture: replace iso=428 if country=="LVA"
capture: replace iso=440 if country=="LTU"
capture: replace iso=442 if country=="LUX"
capture: replace iso=470 if country=="MLT"
capture: replace iso=528 if country=="NLD"
capture: replace iso=554 if country=="NZL"
capture: replace iso=578 if country=="NOR"
capture: replace iso=616 if country=="POL"
capture: replace iso=620 if country=="PRT"
capture: replace iso=642 if country=="ROU" | country=="ROM"
capture: replace iso=703 if country=="SVK"
capture: replace iso=705 if country=="SVN"
capture: replace iso=724 if country=="ESP" | country=="SPA"
capture: replace iso=752 if country=="SWE"
capture: replace iso=756 if country=="SWI"
capture: replace iso=826 if country=="UK" | country=="GBR"
capture: replace iso=840 if country=="USA"
save, replace



*------------------------*
* 3. LOOP OVER COUNTRIES *
*------------------------*


* Loop over countries
levelsof iso, local(countries)
foreach c of local countries {


*------------------------*
* 3.1 Grab model specs
	
	use tmp_modelspecs, clear			// grab model specs for focal country from tmp_modelspecs
	keep if iso==`c'

	local gov = government[1]			// read government model

	global minister = minister[1]		// hand over ministers to est_gov_minister (if selected)
	
	local minority = minority[1]		// grab whether to model minority governments

	global antisys = antisys[1]			// hand over anti-system parties to est_minority
	
	local vetoplayer = vetoplayer[1]	// grab veto player included in vp range
	global vetoplayer = vetoplayer[1]
	tokenize "`vetoplayer'", parse(",")
	local vetoplayer1 `1'				// if "no", do not estimate; else call syntax and hand over institutions to est_vetoplayer


*------------------------*
* 3.2 Estimate	
	
	use basic, clear	// grab pip data
	keep if g101==`c'	// keep focal country

	* Basics
	gen _____ESTIMATES = .
	do techdata/est_basics.do			// 1st and 2nd chamber median, position of president
	save tmp_`c', replace
	
	* Government position
	if 	"`gov'" == "cabmem" {			// government position weighted by cabinet members
		do techdata/est_gov_cabmem.do
	}
	else if "`gov'" == "seats" {		// government position weighted by seat share of coalition parties
		do techdata/est_gov_seats.do
	}
	else if "`gov'" == "portfolios" {	// government position weighted by number of portfolios
		do techdata/est_gov_portfolios.do
	}
	else if "`gov'" == "pm" {			// prime minister's position
		do techdata/est_gov_pm.do
	}
	else if "`gov'" == "minister" {		// portfolio minister's position
		do techdata/est_gov_minister.do
	}
	else if "`gov'" == "pmnegot" {		// prime minister negotiates with minister(s) or cabinet
		do techdata/est_gov_pmnegot.do
	}
	else if "`gov'" == "unanimity" {	// government position under unanimity
		do techdata/est_gov_unanimity.do
	}
	else if "`gov'" == "uwmean" {		// unweighted mean position
		do techdata/est_gov_uwmean.do
	}
	else if "`gov'" == "special_aspm" & `c' == 840 {	// special case: agenda setter USA
		do techdata/est_special_usa_gov.do
	}
	save tmp_`c', replace

	* Minority government
	if "`minority'" == "yes" {			// model minority government
		use tmp_`c', clear
		do techdata/est_minority.do
		save tmp_`c', replace
		}
	else {
		save tmp_`c', replace
	}

	* Veto player						// estimate veto player range
	if "`vetoplayer1'" == "no" {
		save tmp_`c', replace
		}
	else if "`vetoplayer1'" == "special_aspm" & `c' == 756 {	// special case: SWI veto player including referenda
		do techdata/est_special_swi_vp.do
		}
	else if "`vetoplayer1'" == "special_aspm" & `c' == 250 {	// special case: FRA veto player in times of co-habitation
		do techdata/est_special_fra_vp.do
		}
	else if "`vetoplayer1'" == "special_aspm" & "`gov'" == "special_aspm" & `c' == 840 {	// special case: USA veto player in conjunction with gov(special_aspm) only
		do techdata/est_special_usa_vp.do
		}
	else {
		do techdata/est_vetoplayer.do
		save tmp_`c', replace
	}

	
*------------------------*
* 3.3 Prepare time-series and data set	
	
	* Add info to data					// write selected models into data set to facilitate traceability
	gen _____SELECTED_SPECS = .
	clonevar iso = g101
	merge m:1 iso using tmp_modelspecs, nogen keep(match)
	drop iso country
	save tmp_`c', replace
	
	
	* Prepare time-series - QUARTERLY
	keep g101 g102 g103 g104 g105 p601 _____ESTIMATES - vetoplayer
	capture: drop minogov_dummy
	by g101 g105, sort: keep if _n == 1
	rename (g101 g102 g103 g104 g105 p601) (iso country year quarter techq eu)
	order _____SELECTED_SPECS government minister minority antisys vetoplayer, last
	save tsq_`c', replace

	* Prepare time-series - YEARLY
	drop quarter techq
	foreach var of varlist eu _____ESTIMATES - _____SELECTED_SPECS {
		clonevar z`var' = `var'
		by iso year, sort: egen z`var'_zs=mean(`var')
		replace z`var' = z`var'_zs
		drop z`var'_zs `var'
		capture: replace eu = 1 if eu>=0 & eu!=.
		}
	rename z* *
	by iso year, sort: keep if _n == 1
	capture: lab var minoritygov "Indication of minority government throughout the year"
	order _____SELECTED_SPECS government minister minority antisys vetoplayer, last
	save tsy_`c', replace
	
}	// close country loop



*-----------------------*
* 	4. APPEND FILES		*
*-----------------------*


*------------------------*
* 4.1 save outfile

use tmp_modelspecs, clear
summ iso
local first = r(min)
*di `first'

levelsof iso, local(countries)
foreach c of local countries {
	if `c' == `first' {		// use first country file as base...
		use tsq_`c', clear
		save tmpq_append, replace
		erase tsq_`c'.dta
		
		use tsy_`c', clear
		save tmpy_append, replace
		erase tsy_`c'.dta
	}
	else {					// ...and append all other ts files
		use tmpq_append, clear
		append using tsq_`c'
		save, replace
		erase tsq_`c'.dta
		
		use tmpy_append, clear
		append using tsy_`c'
		save, replace
		erase tsy_`c'.dta
	}
}

* Save outfile as specified
local file $save
use tmpq_append, clear
order _____SELECTED_SPECS government minister minority antisys vetoplayer, last
sort iso year
notes replace _dta in 1: These are your ASPM Replication Estimates from TS
save `file'_quarterly, replace

use tmpy_append, clear
order _____SELECTED_SPECS government minister minority antisys vetoplayer, last
sort iso year
notes replace _dta in 1: These are your PIP estimates from TS
save `file'_yearly, replace


*------------------------*
* 4.2 clean folder

* Erase or keep the tmp files for inspection
if "$files" == "erase" {
	use tmp_modelspecs, clear
	levelsof iso, local(countries)
	foreach c of local countries {
		erase tmp_`c'.dta
	}
}

erase basic.dta
erase tmpq_append.dta
erase tmpy_append.dta
erase tmp_modelspecs.dta
clear

noisily: di	in yellow	"You are done! Have good results with the ASPM and PIP data.{break}"	///
						"Please type " in green "quarterly" in yellow " or " in green "yearly" in yellow " to browse the corresponding time-series"	_request(ans)

local usef1 $save
local usef2 $ans
use `usef1'_`usef2', clear
browse
} 	// close quietly bracket
